//
//  HMComposeView.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/30.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import pop
class HMComposeView: UIView {

    //懒加载控件
    private lazy var sloganImageView:UIImageView = UIImageView(image:UIImage(named:"compose_slogan"))
    
    //记录6个菜单按钮
    private lazy var buttonArray:[HMComposeButton] = [HMComposeButton]()
    //记录当前出入的控制器
    var target:UIViewController?
    //取到plist对象的模型数据
    private lazy var composeMenuArray:[HMComposeMenu] = self.loadComposePlistData()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.size = CGSize(width:ScreenWidth,height:ScreenHeight)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setUpUI() {
        backgroundColor = RandomColor()
        //获取模糊图片
        let image = UIImage.screenShot().applyLightEffect()
        let bgImageView = UIImageView(image:image)
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        addChildButton()
        
        //控件布局
        sloganImageView.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
        
        
        }
    
    //添加子控件的方法
    private func addChildButton() {
        //按钮的宽度和高度
        let buttonWidth:CGFloat = 80
        let buttonHeight:CGFloat = 100
        //按钮的间距
        let buttonMargin:CGFloat = (width - 3 * buttonWidth) / 4
        for i in 0..<composeMenuArray.count {
            //列
            let colIndex = i % 3
            //行
            let rowIndex = i / 3
            //获取指定下标的模型
            let composeMenu = composeMenuArray[i]
            
            let button = HMComposeButton()
            //设置tag值
            button.tag = i
            //添加点击事件
            button.addTarget(self, action: #selector(buttonClick(btn:)), for: .touchUpInside)
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            button.size = CGSize(width:buttonWidth,height:buttonHeight)
            button.setImage(UIImage(named:composeMenu.icon!), for: .normal)
            button.setTitle(composeMenu.title, for: .normal)
            addSubview(button)
  
            buttonArray.append(button)
        }
    }
    
    //点击事件实现
    @objc private func buttonClick(btn:UIButton) {
        UIView.animate(withDuration: 0.25, animations: { 
            for button in self.buttonArray {
                button.alpha = 0.2
                if button == btn {
                    //执行放大动画
                    button.transform = CGAffineTransform(scaleX:2,y:2)
                }else {
                    //执行缩小动画
                    button.transform = CGAffineTransform(scaleX:0.2,y:0.2)
                }
            }
            }) { (_) in
                UIView.animate(withDuration: 0.25, animations: { 
                    for button in self.buttonArray {
                        //回到原始大小
                        button.transform = CGAffineTransform.identity
                        button.alpha = 1
                    }
                    }, completion: { (_) in
                        //弹出控制器
//                        let composeVc = HMComposeViewController()
                        //根据tag值获取对应的模型
                        let composeMenu = self.composeMenuArray[btn.tag]
                        //获取对应的class
                        let classType = NSClassFromString(composeMenu.className!) as! UIViewController.Type
                        //根据class创建对象
                        let vc = classType.init()
                        //vc放到导航控制器中
                        let nav = HMNavigationViewController(rootViewController:vc)
                        self.target?.present(nav, animated: true, completion: {
                            //移除罩层
                            self.removeFromSuperview()
                        })
                })
        }
    }
    
    //开启弹簧动画效果
    private func startPopAnimation(isUp:Bool) {
        //向下动画效果需要反转
        if isUp == false {
            buttonArray = buttonArray.reversed()
        }
        
        //遍历数组执行pop动画
        for (i,button) in buttonArray.enumerated() {
            let popAnimation = POPSpringAnimation(propertyNamed:kPOPViewCenter)
            if isUp {
                popAnimation?.toValue = NSValue(cgPoint:CGPoint(x:button.centerX,y:button.centerY - 350))
            }else  {
                popAnimation?.toValue = NSValue(cgPoint:CGPoint(x:button.centerX,y:button.centerY + 350))
            }
            
            //初始速度
            popAnimation?.springSpeed = 10
            //抖动幅度
            popAnimation?.springBounciness = 10
            //开始动画时间
            popAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //执行动画
            button.pop_add(popAnimation, forKey: nil)
            
        }
    }
    
    func show(target:UIViewController) {
        self.target = target
        target.view.addSubview(self)
        //开启弹簧动画效果
        startPopAnimation(isUp: true)
    }
    
    //读取plist文件数据的方法
    private func loadComposePlistData()-> [HMComposeMenu] {
        //获取plist文件路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        //根据路径获取plist文件的数据
        let dicArray = NSArray(contentsOfFile:path)!
        //字典转模型
        let modelArray = NSArray.yy_modelArray(with: HMComposeMenu.self, json: dicArray)! as! [HMComposeMenu]
        //返回模型
        return modelArray
        
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        startPopAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            //移除罩层
            self.removeFromSuperview()
        }
        
    }
}
